package com.zjitc.serviceedu.controller;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.zjitc.common.exception.AuthException;
import com.zjitc.common.utils.RespBean;
import com.zjitc.serviceedu.entity.EduVideo;
import com.zjitc.serviceedu.service.EduVideoService;

import com.zjitc.serviceedu.utils.InitVideoCilent;
import com.zjitc.serviceedu.utils.VideoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 赵诚挚
 * @since 2024-09-20
 */
@RestController
@RequestMapping("/serviceedu/edu-video")
@Api(tags = "视频小结模块")
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;

    @ApiOperation("添加小结")
    @PostMapping("addVideo")
    public RespBean addVideo(EduVideo eduVideo) {
        boolean save = videoService.save(eduVideo);
        return RespBean.success().data("save", save).msg("添加成功");

    }

    @ApiOperation("删除小结")
    @DeleteMapping("deleteVideo/{id}")
    public RespBean deleteVideo(@PathVariable Long id) {
        boolean rows = videoService.removeById(id);
        if (!rows) {
            throw new AuthException("删除失败");
        }
        return RespBean.success().data("rows", rows).msg("删除删除");
    }

    @ApiOperation("查询小结详情")
    @GetMapping("getVideo/{id}")
    public RespBean updateVideo(@PathVariable Long id) {
        EduVideo eduVideo = videoService.getById(id);
        return RespBean.success().data("data", eduVideo).msg("查询成功");
    }


    @ApiOperation("更新小结")
    @PutMapping("updateVideo")
    public RespBean updateVideo(EduVideo eduVideo) {
        boolean rows = videoService.updateById(eduVideo);
        if (!rows) {
            throw new AuthException("更新失败");
        }
        return RespBean.success().data("rws", rows).msg("更新成功");
    }

    @ApiOperation("上传视频")
    @PostMapping("upload")
    public RespBean uploadVideo(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestParam("file") MultipartFile file, EduVideo eduVideo) throws Exception {

        // 调用视频上传服务
        RespBean uploadRespBean = videoService.upload(file, eduVideo);  // 假设 upload 返回 RespBean
        Map<String, Object> videoData = (Map<String, Object>) uploadRespBean.getData().get("data");  // 获取视频数据

        String videoId = "";
        float duration = 0;
        long size = 0;

        if (videoData != null) {
            videoId = (String) videoData.get("videoId");
            duration = (Float) videoData.get("duration");
            size = (Long) videoData.get("size");
        }

        // 将视频信息放入 data 中
        Map<String, Object> data = new HashMap<>();
        data.put("videoId", videoId);  // 确保这里是正确的视频 ID
        data.put("duration", duration);
        data.put("size", size);

        // 返回成功的响应
        return RespBean.success().data("data", data).msg("视频上传成功");
    }


    @ApiOperation("删除视频")
    @DeleteMapping("removeVideo/{videoId}")
    public RespBean removeVideo(@PathVariable String videoId) {
        try {
            DefaultAcsClient client = InitVideoCilent.initVodClient(
                    VideoUtils.ACCESS_KEY_ID,
                    VideoUtils.ACCESS_KEY_SECRET);

            DeleteVideoRequest request = new DeleteVideoRequest();

            request.setVideoIds(videoId);

            DeleteVideoResponse response = client.getAcsResponse(request);

            System.out.print("RequestId = " + response.getRequestId() + "\n");
            return RespBean.success().data("data", response).msg("删除视频成功");

        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            throw new AuthException("视频删除失败");

        }
    }
    @ApiOperation("获取视频凭证")
    @GetMapping("getPlayAuth/{videoId}")
    public RespBean getPlayAuth(@PathVariable("videoId") String videoId) throws Exception {

        //获取阿里云存储相关常量
        String accessKeyId = VideoUtils.ACCESS_KEY_ID;
        String accessKeySecret = VideoUtils.ACCESS_KEY_SECRET;

        //初始化
        DefaultAcsClient client = InitVideoCilent.initVodClient(accessKeyId, accessKeySecret);

        //请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);

        //响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);

        //得到播放凭证
        String playAuth = response.getPlayAuth();

        //返回结果
        return RespBean.success().msg("获取凭证成功").data("playAuth", playAuth);
    }

    @GetMapping("/getPlayURL")
    public RespBean getPlayURL(@RequestParam("playAuth") String playAuth, @RequestParam("videoId") String videoId) {
        // 根据 playAuth 和 videoId 生成播放 URL 的逻辑
        // 例如通过阿里云 SDK 获取播放地址
        String playURL = videoService.getPlayURL(playAuth, videoId);
        return RespBean.success().data("playURL", playURL);
    }
}
